import cv2
import time
import threading
cap=cv2.VideoCapture(0)
lap_list=[]
i=1        
exp=-8 

# 用于定时保存的变量
tim = None
# 用于保存当前帧的全局变量
current_frame = None
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
cap.set(cv2.CAP_PROP_FPS, 30)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1.0) 

# 鼠标点击事件回调函数
def mouse_callback(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:  # 左键点击
        if current_frame is not None:
            time_stamp = int(time.time())
            cv2.imwrite(f'captured_photos/pic_{time_stamp}.jpg', current_frame)
            print(f'照片保存为captured_photos/pic_{time_stamp}.jpg')

# 创建窗口并设置属性
cv2.namedWindow("image capture", cv2.WINDOW_NORMAL)
cv2.setWindowProperty("image capture", cv2.WND_PROP_TOPMOST, 1)
cv2.resizeWindow("image capture", 640,360)
# 注册鼠标事件回调
cv2.setMouseCallback("image capture", mouse_callback)
time.sleep(0.5)
while cap.isOpened():
    ret,frame=cap.read()
    if not ret:
        break
    # 更新当前帧
    current_frame = frame

    frame=cv2.GaussianBlur(frame,(i,i),0)

    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    lap_var=cv2.Laplacian(gray,cv2.CV_64F).var()
    if len(lap_list)<30:
        lap_list.append(lap_var)
    else:
        lap_list.pop(0)
        lap_list.append(lap_var)
    lap_var_avg=sum(lap_list)/len(lap_list)

    key = cv2.waitKey(1) & 0xFF
    # 使用更简洁的条件判断，将具有相同操作的键分组
    if key in (ord('q'), 27):  # 'q'键或ESC键退出
        break
    elif key in (ord('s'), ord(' ')):  # 's'键或空格键保存照片
        time_stamp = int(time.time())
        cv2.imwrite(f'captured_photos/pic_{time_stamp}.jpg', frame)
        print(f'照片保存为captured_photos/pic_{time_stamp}.jpg')
    elif key == ord('t'):  # 定时3秒后拍照 
        # 设置定时保存时间为当前时间+3秒
        tim = time.time() + 3
        print("将在3秒后保存照片")
    elif key == ord('+'):  # '+'键增加滤波核大小
        i = min(i + 2, 15)  # 限制滤波核大小最大为15
        print(f'{f"滤波核大小增加为:{i}":<20}', end='\r', flush=True)  # 固定宽度20，确保覆盖整行
    elif key == ord('-'):  # '-'键减小滤波核大小
        i = max(i - 2, 1)  # 限制滤波核大小最小为1
        print(f'{f"滤波核大小减小为:{i}":<20}', end='\r', flush=True)  # 固定宽度20，确保覆盖整行
    elif key == ord('9'):  
        exp = min(exp + 1, -6)
        print(f'{f"曝光时间增加为:{exp}":<20}', end='\r', flush=True)  # 固定宽度20，确保覆盖整行
        cap.set(cv2.CAP_PROP_EXPOSURE, exp)
    elif key == ord('3'):  
        exp = max(exp - 1, -10)
        print(f'{f"曝光时间减小为:{exp}":<20}', end='\r', flush=True)  # 固定宽度20，确保覆盖整行
        cap.set(cv2.CAP_PROP_EXPOSURE, exp)
    elif key == ord('0'):  
        print(f'{f"自动曝光已启用":<20}', end='\r', flush=True)  # 固定宽度20，确保覆盖整行
        cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1.0)

    # 检查定时保存时间是否已到
    if tim and time.time() >= tim:
        time_stamp = int(time.time())
        cv2.imwrite(f'captured_photos/pic_{time_stamp}.jpg', frame)
        print(f'照片保存为captured_photos/pic_{time_stamp}.jpg')
        tim = None  # 重置定时保存时间  

    cv2.putText(frame,f'LapVar: {lap_var_avg:.2f}',
    (10,30),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2)

    cv2.imshow("image capture",frame)

cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1.0)
cap.release()
cv2.destroyAllWindows()
print(f'{f"自动曝光已启用":<20}')
